import http from 'wechat-http'
http.baseURL = 'http://toutiao.itheima.net'
//请求拦截器
http.intercept.request = (config) => {
  const token = getApp().token
  if (token) {
    config.header = {
      Authorization: token,
      ...config.header,
    }
  }
  return config
}
//响应拦截器
http.intercept.response = async (res) => {
  console.log(res, '祖传的res')
  //处理refresh_token失效
  if (res.statusCode === 500 && res.config.url.endsWith('authorizations')) {
    wx.redirectTo({
      url: '/pages/login/login',
    })
  }

  if (res.statusCode === 401) {
    //请求刷新token
    const {
      data: { token },
    } = await wx.http({
      url: '/v1_0/authorizations',
      method: 'put',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: getApp().refresh_token,
      },
    })
    //覆盖原来的token
    getApp().setToken(token)
    //发送用户原来的请求
    wx.http({
      ...res.config,
      header: {
        Authorization: getApp().token,
      },
    })
  }
  return res.data
}
/**
 * 挂载到wx全局对象
 */
wx.http = http
